package com.st.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.st.util.AliOSSUtils;
import org.bytedeco.ffmpeg.avformat.AVFormatContext;
import org.bytedeco.ffmpeg.global.avformat;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacpp.PointerPointer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
 * @version V 1.0
 * @auther ROG
 * @date 2024/10/24
 * @project_name back
 * @description
 */
@RestController
@RequestMapping(path = "file")
public class FileController {

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @RequestMapping(path = "upload", method = RequestMethod.POST)
    public AjaxResult uploadFile(MultipartFile file) throws IOException {

        String url = aliOSSUtils.upload(file);

        return AjaxResult.success("success", url);
    }

    @RequestMapping(path = "uploadVideo", method = RequestMethod.POST)
    public AjaxResult uploadVideo(MultipartFile file) throws Exception {

        InputStream inputStream = file.getInputStream();

        String url = aliOSSUtils.upload(file,inputStream);

        long videoDuration = getVideoDuration(inputStream);

        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("url",url);
        map.put("times",videoDuration);

        return AjaxResult.success("success", map);
    }


    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam String fileUrl) {
        try {
            // 根据文件URL建立连接
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            // 检查是否连接成功
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return ResponseEntity.status(responseCode).body(null);
            }

            // 获取文件输入流
            InputStream inputStream = connection.getInputStream();
            String fileName = extractFileName(fileUrl);

            // 设置响应头，让前端能够下载文件
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(connection.getContentLength())
                    .body(new InputStreamResource(inputStream));

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    // 从URL中提取文件名
    private String extractFileName(String fileUrl) {
        return fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
    }

    private long getVideoDuration(InputStream inputStream) throws Exception {
        avutil.av_log_set_level(avutil.AV_LOG_QUIET); // 静音日志输出
        avformat.avformat_network_init(); // 初始化 FFmpeg 格式库

        AVFormatContext pFormatContext = avformat.avformat_alloc_context();

        // 打开输入视频文件并获取格式上下文
        if (avformat.avformat_open_input(pFormatContext, "-", null, null) != 0) {
            throw new RuntimeException("无法打开视频流");
        }

        // 读取媒体文件数据
        if (avformat.avformat_find_stream_info(pFormatContext, (PointerPointer<?>) null) < 0) {
            throw new RuntimeException("无法读取视频流信息");
        }

        // 获取视频时长，单位为微秒（us），需要转换为秒
        long durationInMicroSeconds = pFormatContext.duration();
        long durationInSeconds = durationInMicroSeconds / 1000000;

        // 释放格式上下文
        avformat.avformat_close_input(pFormatContext);
        avformat.avformat_free_context(pFormatContext);

        return durationInSeconds;
    }
}
